package com.e2j.lib;

import com.alibaba.fastjson2.JSONObject;
import com.e2j.server.domin.HeaderData;
import com.e2j.utils.json.IJsonData;
import com.e2j.utils.json.JsonStringData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Excel数据配置文件加载器
 * @author 杨永良
 * @date 2022/7/13 9:51
 **/
public class DefinitionDataset {
    static final Logger logger = (Logger) LoggerFactory.getLogger(DefinitionDataset.class);

    private List<ExcelLibDefinition> excelLibDefinitions;

    private HeaderData header;

    /**
     * 键值获取定义文件，Key:dataFullName
     */
    private Map<String, ExcelLibDefinition> definitions;

    private Map<String, ExcelLibDefinitionTable> definitionTables;

    private String namespace = null;

    private boolean isDone = false;

    private JSONObject jsonObj;

    public JSONObject getJsonObj() {
        return jsonObj;
    }

    public boolean loadDefinition(String jsonStr) throws NoSuchFieldException {
        IJsonData jsonData;

        try {
            jsonData = new JsonStringData(jsonStr);
        } catch (Exception e) {
            logger.error("Excel数据包加载：打开definition失败");
            return false;
        }
        excelLibDefinitions = ExcelLibTools.LoadDefinition(jsonData);
        excelLibDefinitions.sort(ExcelLibDefinition::compareTo);
        definitionTables = ExcelLibTools.LoadDefinitionTable(jsonData);
        jsonObj = JSONObject.parseObject(jsonData.getJsonStr());
        JSONObject jsonHead = JSONObject.parseObject(jsonObj.getString("header"));
        header = new HeaderData();
        header.parseFromJson(jsonHead);

        logger.info("Excel数据包，定义文件加载个数：" + excelLibDefinitions.size());
        definitions = new HashMap<>();
        for (ExcelLibDefinition excelLibDefinition : excelLibDefinitions) {
            definitions.put(excelLibDefinition.getDataFullName(), excelLibDefinition);
        }
        return true;
    }

    public List<ExcelLibDefinition> getExcelLibDefinitions() {
        return excelLibDefinitions;
    }

    public Map<String, ExcelLibDefinition> getDefinitions() {
        return definitions;
    }

    public Map<String, ExcelLibDefinitionTable> getDefinitionTables() {
        return definitionTables;
    }

    public HeaderData getHeader() {
        return header;
    }

    public boolean isDone() {
        return isDone;
    }

    public void setDone(boolean done) {
        isDone = done;
    }
}
